package com.zy.community.mini.service.index;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.zy.community.common.core.domain.r.ZyResult;
import com.zy.community.community.domain.ZyVisitor;
import com.zy.community.community.mapper.ZyVisitorMapper;
import com.zy.community.framework.security.mini.MiniContextUtils;
import com.zy.community.mini.factory.VisitorFactory;
import com.zy.community.web.controller.mini.index.dto.VisitorDto;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 访客服务
 */
@Service
public class MiniVisitorService {
    @Resource
    private ZyVisitorMapper zyVisitorMapper;
    @Resource
    private VisitorFactory visitorFactory;

    /**
     * 保存访客记录
     *
     * @param visitorDto 访客记录
     * @return 保存结果
     */
    public ZyResult<String> saveVisitor(VisitorDto visitorDto) {
        if (visitorDto == null) return ZyResult.fail(400, "访客信息不能为空");
        ZyVisitor visitorByDto = visitorFactory.createVisitorByDto(visitorDto);
        zyVisitorMapper.insert(visitorByDto);
        return ZyResult.data(visitorByDto.getVisitorId()+"");
    }

    /**
     * 查找最近的3位访客
     *
     * @return 结果
     */
    public ZyResult<List<VisitorDto>> findLatest3Visitor(Long communityId) {
        String openId = MiniContextUtils.getOpenId();
        if (StringUtils.isEmpty(openId)) return ZyResult.fail(401, "用户未认证");
        List<ZyVisitor> zyVisitors = zyVisitorMapper.selectList(new QueryWrapper<ZyVisitor>()
                .eq("create_by_open_id", openId)
                .eq("community_id", communityId)
                .orderByDesc("create_time")
                .last(" limit 3")
        );
        return ZyResult.data(zyVisitors.stream().map(visitor -> visitorFactory.transFromVisitor(visitor)).collect(Collectors.toList()));

    }

    /**
     * 查询当前用户的访客记录(分页)
     *
     * @param size    每页记录数
     * @param current 页码
     * @param communityId 社区Id
     * @return 分页记录
     */
    public ZyResult<PageInfo<VisitorDto>> findVisitorsByPage(Integer size, Integer current, Long communityId) {
        String openId = MiniContextUtils.getOpenId();
        if (StringUtils.isEmpty(openId)) return ZyResult.fail(401, "用户未认证");
        PageHelper.startPage(current,size);
        List<VisitorDto> visitorsByPage = zyVisitorMapper.findVisitorsByPage(communityId, openId);
        return ZyResult.data(new PageInfo<VisitorDto>(visitorsByPage));
    }

}
